package com.breeze.blockchain.service.impl;

import static com.breeze.blockchain.mybatis.entity.table.SettingTable.SETTING;

import com.breeze.blockchain.common.enums.RedisKeyEnum;
import com.breeze.blockchain.common.enums.SettingKeyEnum;
import com.breeze.blockchain.mybatis.entity.SettingDo;
import com.breeze.blockchain.mybatis.mapper.SettingMapper;
import com.breeze.blockchain.service.SettingService;
import com.breeze.components.redis.util.RedisUtil;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import java.util.Optional;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 配置表 服务层实现。
 *
 * @author breeze
 * @since 2024-05-11 23:21:51
 */
@Service
public class SettingServiceImpl extends ServiceImpl<SettingMapper, SettingDo>
    implements SettingService {

  @Resource RedisUtil redisUtil;

  @Override
  public SettingDo getKeyByValue(String key) {
    return getKeyByValueOpt(key).orElse(null);
  }

  @Override
  public Optional<SettingDo> getKeyByValueOpt(String key) {
    return queryChain().where(SETTING.KEY.eq(key)).eq(SettingDo::getKey, key).oneOpt();
  }

  @Override
  public Optional<String> getKeyValue(SettingKeyEnum setting) {
    return Optional.ofNullable(
        redisUtil.getCacheObject(RedisKeyEnum.SYS_SETTING.getKey(setting.key())));
  }

  @Override
  public void putCache(SettingDo setting) {
    var key = RedisKeyEnum.SYS_SETTING.getKey(setting.getKey());
    redisUtil.setCacheObject(key, setting.getValue());
  }

  @Transactional(rollbackFor = Throwable.class)
  @Override
  public boolean addOrUpdate(SettingDo setting) {
    setting.setId(getKeyByValueOpt(setting.getKey()).map(SettingDo::getId).orElse(null));
    var saveOrUpdate = this.saveOrUpdate(setting);
    putCache(setting);
    return saveOrUpdate;
  }
}
